<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-select v-model="query.QueryType" placeholder="查询方式" class="handle-select mr10">
          <el-option key="1" label="物资名" value="name"></el-option>
          <el-option key="2" label="物资ID" value="item_id"></el-option>
        </el-select>
        <div>
          <el-input v-model="query.SearchInput" placeholder="请输入" class="handle-input mr10"></el-input>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button type="primary" :icon="Plus" @click="addNew()">新增</el-button>
        </div>
      </div>

      <el-table
          :data="tableData"
          height="550"
          border class="table" ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column label="序号" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="item_id" label="物资ID" align="center"></el-table-column>
        <el-table-column prop="name" label="物资名" align="center"></el-table-column>
        <el-table-column prop="total_num" label="物资总数" align="center"></el-table-column>
        <el-table-column prop="remain_num" label="物资当前保有数" align="center"></el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <div v-if="HoverControl == scope.$index" @mouseleave="handleMouseLeave" class="temp">
              <el-button text @click="changeTotal(scope.$index,scope.row)">
                总数更改
              </el-button>
              <el-button text @click="changeRemain(scope.$index,scope.row)">
                当前保有数更改
              </el-button>
            </div>
            <el-button v-else text :icon="Sort" @mouseover="handleMouseOver(scope.$index)">
              物资数更改
            </el-button>
            <el-button text :icon="Edit" @click="changeName(scope.$index, scope.row)">
              物资名更改
            </el-button>
            <el-button text :icon="Delete" class="red" @click="handleDelete(scope.$index, scope.row)">
              删除该物资
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref, watch} from 'vue';
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Edit, Search, Sort} from '@element-plus/icons-vue';
import axios from "axios";
import {Plus} from "@element-plus/icons-vue/dist/index";


interface Device {
  item_id: string;
  name: string;
  total_num: string;
  remain_num: string;

  [key: string]: string;
}

const query = reactive({
  QueryType: 'username',
  SearchInput: '',
  pageIndex: 1,
  pageSize: 10
});

const HoverControl = ref(-1)
const allData = ref<Device[]>([]);
const tableData = ref<Device[]>([]);
const handleMouseOver = (index: number) => {
  HoverControl.value = index
}
const handleMouseLeave = () => {
  HoverControl.value = -1
}
// 获取表格数据
const getData = () => {
  // TODO 获取全部设备
  // axios.get(`http://localhost:8080/item`)
  //     .then(res=>{
  //       allData.value=res.data.data
  //       console.log(allData.value)
  //       //   将归还状态置为 已归还/未归还
  //       for(let i=0;i<allData.value.length;i++){
  //         if(allData.value[i].return_state=="0"){
  //           allData.value[i].return_state="未归还"
  //           allData.value[i].return_time="——"
  //         }else{
  //           allData.value[i].return_state="已归还"
  //         }
  //       }
  //       tableData.value = allData.value
  //     })
  allData.value = [
    {
      item_id: "1",
      name: "物资1",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "2",
      name: "物资2",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "3",
      name: "物资3",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "4",
      name: "物资4",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "5",
      name: "物资5",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "6",
      name: "物资6",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "7",
      name: "物资7",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "8",
      name: "物资8",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "9",
      name: "物资9",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "10",
      name: "物资10",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "11",
      name: "物资11",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "12",
      name: "物资12",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "13",
      name: "物资13",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "14",
      name: "物资14",
      total_num: "10",
      remain_num: "5"
    },
    {
      item_id: "15",
      name: "物资15",
      total_num: "10",
      remain_num: "5"
    },
  ]
  tableData.value = allData.value
};
getData();

// 查询操作
const handleSearch = () => {
  if (query.SearchInput == "") {
    tableData.value = allData.value
  } else {
    tableData.value = []
    for (let i = 0; i < allData.value.length; i++) {
      if (allData.value[i][query.QueryType] != null && allData.value[i][query.QueryType].toLowerCase().indexOf(query.SearchInput.toLowerCase()) != -1) {
        tableData.value.push(allData.value[i])
      }
    }
  }
};

const addNew = () => {
  //TODO 新增物资请求
  ElMessageBox.confirm('确定要新增吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        // 弹出框输入的物资名
        let inputName = ""
        ElMessageBox.prompt('请输入物资名', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
            .then(({value}) => {
              inputName = value
              // 弹出框输入的物资总数
              let inputTotal = 0
              ElMessageBox.prompt('请输入物资总数', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /\d+/,
                inputErrorMessage: '请输入数字'
              })
                  .then(({value}) => {
                    inputTotal = Number(value)

                    axios.post(`http://localhost:8080/item`, {
                      name: inputName,
                      total_num: inputTotal,
                      remain_num: inputTotal
                    })
                        .then(res => {
                          if (res.data.status === 0) {
                            ElMessage.success("新增物资成功!")
                            getData()
                          } else {
                            ElMessage.error("新增物资失败!")
                          }
                        })
                  })
                  .catch(() => {
                  });
            })
            .catch(() => {
            });
      })
      .catch(() => {
      });
}

// 分页导航
const handlePageChange = (val: number) => {
  query.pageIndex = val;
  getData();
};

// 表格编辑时弹窗和保存
const editVisible = ref(false);
let form = reactive({
  name: '',
  address: ''
});

const changeTotal = (index: number, row: any) => {
  //TODO 更改物资总数请求
  ElMessageBox.confirm('确定要更改物资总数吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        // 弹出框输入的物资总数
        let inputTotal = 0
        ElMessageBox.prompt('请输入物资总数', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\d+/,
          inputErrorMessage: '请输入数字'
        })
            .then(({value}) => {
              inputTotal = Number(value)
              // 判断输入的物资总数是否小于当前保有数
              if (inputTotal < row.remain_num) {
                ElMessage.error("物资总数小于当前保有数，无法更改物资总数!")
                return
              }
              axios.put(`http://localhost:8080/item`, {
                item_id: row.item_id,
                name: row.name,
                total_num: inputTotal,
                remain_num: row.remain_num
              })
                  .then(res => {
                    if (res.data.status === 0) {
                      ElMessage.success("更改物资总数成功!")
                      getData()
                    } else {
                      ElMessage.error("更改物资总数失败!")
                    }
                  })
            })
            .catch(() => {
            });
      })

};

const changeRemain = (index: number, row: any) => {
  //TODO 更改物资当前保有数请求
  ElMessageBox.confirm('确定要更改物资当前保有数吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        // 弹出框输入的物资当前保有数
        let inputRemain = 0
        ElMessageBox.prompt('请输入物资当前保有数', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\d+/,
          inputErrorMessage: '请输入数字'
        })
            .then(({value}) => {
              inputRemain = Number(value)
              // 判断输入的物资当前保有数是否大于物资总数
              if (inputRemain > row.total_num) {
                ElMessage.error("物资当前保有数大于物资总数，无法更改物资当前保有数!")
                return
              }
              axios.put(`http://localhost:8080/item`, {
                item_id: row.item_id,
                name: row.name,
                total_num: row.total_num,
                remain_num: inputRemain
              })
                  .then(res => {
                    if (res.data.status === 0) {
                      ElMessage.success("更改物资当前保有数成功!")
                      getData()
                    } else {
                      ElMessage.error("更改物资当前保有数失败!")
                    }
                  })
            })
            .catch(() => {
            });
      })
};

const changeName = (index: number, row: any) => {
  //TODO 更改物资名请求
  ElMessageBox.confirm('确定要更改物资名吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        // 弹出框输入的物资名
        let inputName = ""
        ElMessageBox.prompt('请输入物资名', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
            .then(({value}) => {
              inputName = value
              axios.put(`http://localhost:8080/item`, {
                item_id: row.item_id,
                name: inputName,
                total_num: row.total_num,
                remain_num: row.remain_num
              })
                  .then(res => {
                    if (res.data.status === 0) {
                      ElMessage.success("更改物资名成功!")
                      getData()
                    } else {
                      ElMessage.error("更改物资名失败!")
                    }
                  })
            })
            .catch(() => {
            });
      })
};


// 删除操作
const handleDelete = (index: number, row: any) => {
  //TODO 删除物资请求
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        axios.delete(`http://localhost:8080/item/` + row.item_id)
            .then(res => {
              if (res.data.status === 0) {
                ElMessage.success("删除物资成功!")
                getData()
              } else {
                ElMessage.error("删除物资失败!")
              }
            })
      })
      .catch(() => {
      });
};

const router = useRouter()
watch(
    () => router.currentRoute.value,
    (newRoute) => {
      if (newRoute.name == "user") {
        getData()
      }
    },
    {immediate: true}
);
</script>

<style scoped>
.handle-box {
  width: auto;
  margin-bottom: 20px;
  display: flex;
  justify-content: left;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #F56C6C;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.temp {
  display: flex;
  justify-content: center;
  width: 80%;
  margin: 0 auto;
}
</style>